<!-- 多个玩家调控 -->
<template>
  <el-dialog :modelValue="props.show" title="玩家调控列表" width="85%" top="6vh" :close-on-click-modal="false"
    :close-on-press-escape="false" @close="handleClose">
    <div v-loading="indexStore.moduleLoading" class="dialogMaxBatch">
      <SearchTable v-loading="indexStore.moduleLoading" :query="data.query" :list="data.list" :total="data.total" :showSet="false" :showExport="false" :showPagination="data.userControlList.length ? true : false"
        @changeSize="changeSize" @changePage="changePage" @search="getSearchList" @select="playerControl" @reset="onHideDetails(true)">
        <template #form>
          <Operator ref="OperatorRef" @query="queryItem" :allShow="false" />
          <el-form-item label="">
            <el-select class="selectWidth120" v-model="data.query.search_type" placeholder="请选择">
              <el-option v-for="item in data.conditionList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-input class="width200" v-model="data.query.search_value" placeholder="请输入" clearable
              onKeyUp="value=value.replace(/[\W]/g,'')" />
          </el-form-item>
          <el-form-item label="">
            <el-select class="selectWidth150" v-model="data.query.time_type" placeholder="请选择">
              <el-option label="创建时间" :value="1" />
              <el-option label="最后登录时间" :value="2" />
            </el-select>
            <el-date-picker v-model="data.query.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
              end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable :disabled-date="indexStore.disabledDateTime"/>
          </el-form-item>
          <el-form-item label="今日下注：">
            <el-input class="width200" v-model="data.query.today_bet" placeholder="请输入今日下注" clearable
            onKeyUp="value=value.replace(/[\W]/g,'')" />
          </el-form-item>
          <el-form-item label="历史下注：">
            <el-input class="width200" v-model="data.query.total_bet" placeholder="请输入历史下注" clearable
            onKeyUp="value=value.replace(/[\W]/g,'')" />
          </el-form-item>
          <el-form-item label="今日输赢：">
            <el-input class="width200" v-model="data.query.today_game_income" placeholder="请输入今日输赢" clearable
            onKeyUp="value=value.replace(/[\W]/g,'')" />
          </el-form-item>
          <el-form-item label="历史输赢：">
            <el-input class="width200" v-model="data.query.total_game_income" placeholder="请输入历史输赢" clearable
            onKeyUp="value=value.replace(/[\W]/g,'')" />
          </el-form-item>
        </template>
        <template #button>
          <el-button type="warning" :disabled="data.userControlList.length ? false : true" @click="data.isControlShow = true">调控设置</el-button>
        </template>
        <template #table>
          <el-table-column type="selection" width="45" />
          <template v-for="(item, index) in data.fields" :key="index">
            <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width" show-overflow-tooltip>
              <template #header>
                <el-tooltip v-if="item.tips" effect="dark" placement="top">
                  <template #content>
                    {{ item.tips }}
                  </template>
                  <el-icon class="ques-tips">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                {{ item.label }}
              </template>
              <template v-if="item.prop == 'agent_id'" #default="scope">
                {{ selectToLabel(indexStore.agentArray, scope.row.agent_id) }}
              </template>
              <template v-if="item.prop == 'today_bet'" #default="scope">
                <span class="colorText"> {{ BigWan(scope.row.today_bet) }} </span>
              </template>
              <template v-if="item.prop == 'total_bet'" #default="scope">
                <span class="colorText"> {{ BigWan(scope.row.total_bet) }} </span>
              </template>
              <template v-if="item.prop == 'today_game_income'" #default="scope">
                <span :class="colorClass(scope.row.today_game_income)"> {{ BigWan(scope.row.today_game_income) }}
                </span>
              </template>
              <template v-if="item.prop == 'total_game_income'" #default="scope">
                <span :class="colorClass(scope.row.total_game_income)"> {{ BigWan(scope.row.total_game_income) }}
                </span>
              </template>
              <template v-if="item.prop == 'amount'" #default="scope">
                <span class="colorText"> {{ BigWan(scope.row.amount) }} </span>
              </template>
              <template v-if="item.prop == 'is_online'" #default="scope">
                <el-tag :type="scope.row.is_online ? 'success' : 'danger'">{{
                  selectToLabel(OnlineState, scope.row.is_online) }}</el-tag>
              </template>
              <template v-if="item.prop == 'created_at_stamp'" #default="scope">
                {{ setTimestampTime(scope.row.created_at_stamp) }}
              </template>
              <template v-if="item.prop == 'last_login_stamp'" #default="scope">
                {{ setTimestampTime(scope.row.last_login_stamp) }}
              </template>
              <template v-if="item.prop == 'last_play_game_id'" #default="scope">
                <span v-if="scope.row.last_play_game_id">
                  {{ selectToLabel(indexStore.gameArray, scope.row.last_play_game_id) }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </template>
        </template>
      </SearchTable>
    </div>
  </el-dialog>

  <!-- 批量玩家调控 -->
  <el-dialog :modelValue="data.isControlShow" title="玩家调控" width="60%" top="20vh" :close-on-click-modal="false"
    :close-on-press-escape="false" @close="onHideDetails">
    <div v-loading="indexStore.moduleLoading" class="dialogMaxHeight">
      <div class="padding10">
        <form-item title="调控玩家">
          <div class="flexWrap">
            <span class="margin5" v-for="(item, index) in data.userControlList" :key="index">
              【{{ item.account3d_id }}】{{ item.account3d }}
            </span>
          </div>
        </form-item>
        <form-item title="调控游戏" :pass="true" value="game_id">
          <el-select class="imWidth100" v-model="data.userControl.game_ids" placeholder="请选择游戏" filterable multiple
            @change="chooseGameType">
            <el-option label="全部" :value="-1" />
            <el-option v-for="(item, index) in data.gameList" :key="index"
              :label="'【' + item.value + '】' + item.label" :value="item.value"/>
          </el-select>
        </form-item>
        <form-item title="自动解除控制" value="auto_cancel_rtp">
          <el-input-number v-model="data.userControl.auto_cancel_rtp" :min="0" :max="99999999999999999999" :precision="0"
          class="width150" placeholder="请输入RTP设定值" clearable :controls="false" />%
          <span class="tipsText">(玩家在游戏内达到设定RTP解除控制，恢复正常)</span>
        </form-item>
        <form-item title="RTP" :pass="true" value="rtp">
          <el-select class="width150" v-model="data.userControl.rtp" placeholder="请选择RTP" filterable>
            <el-option v-show="item && item==200?operatorTypeShow:true" v-for="(item, index) in data.rtpList" :key="index" :label="item + '%'" :value="item" />
          </el-select>
          <el-button class="marginL20" type="success" :disabled="data.userControl.game_ids.length ? false : true"
            @click="addControl">新增调控</el-button>
        </form-item>
      </div>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, watch, ref } from 'vue'
import { ElMessage } from 'element-plus'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import { throttle, selectToLabel, colorClass, setCommaToArr } from '@/utils/index'
import { setTimestampTime, setTimeValue, getSevenWeek } from '@/utils/time'
import { getPlayer, changeAllControlUser } from '@/api/player'
import { getOperatorTiger } from '@/api/game'
import { BigWan, BigTimeWan, BigHundred, BigTimeHundred } from '@/utils/math'
import { OnlineState } from '@/config/eunm'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const props = defineProps({
  show: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  agentItem: {
    type: Object,
    default: () => {
      return {
        agent_id: 1,
        operated_id: 0,
      }
    }
  },
})

const data = reactive({
  query: {
    page: 1,
    size: 50,
    status: -1,
    search_type: 1,
    search_value: '',
    time_type: 1,
    agent_id: -1,
    operated_id: -1,
    is_online: -1,
    today_bet: '',
    total_bet: '',
    today_game_income: '',
    total_game_income: '',
    date: getSevenWeek()
  },
  list: [],
  total: 0,
  fields: [
    { label: '创建时间', prop: 'created_at_stamp', width: '170', visible: true, tips: '玩家的注册时间' },
    { label: '最后登录时间', prop: 'last_login_stamp', width: '170', visible: true, tips: '玩家最近一次上线的时间' },
    { label: '平台ID', prop: 'account3d_id', width: '150', visible: true, tips: '玩家ID编号，唯一' },
    { label: '平台昵称', prop: 'account3d', width: '200', visible: true, tips: '玩家名称' },
    { label: '商户昵称', prop: 'agent_id', width: '150', visible: true, tips: '玩家所属商户' },
    { label: '今日下注', prop: 'today_bet', width: '', visible: true, sortable: true, tips: '玩家今日的下注数量' },
    { label: '历史下注', prop: 'total_bet', width: '', visible: true, sortable: true, tips: '玩家的历史总下注数量' },
    { label: '今日输赢', prop: 'today_game_income', width: '', visible: true, sortable: true, tips: '玩家今日输赢情况，正为玩家赢，负则反之' },
    { label: '历史输赢', prop: 'total_game_income', width: '', visible: true, sortable: true, tips: '玩家的历史输赢情况，正为玩家赢，负为输' },
    { label: '余额', prop: 'amount', width: '', visible: true, sortable: true, tips: '玩家当前持有余额数量' },
  ],
  conditionList: [
    { label: '平台ID', value: 1 },
    { label: '平台昵称', value: 3 }
  ],
  reasonBan: '',
  banType: 1,
  isBanShow: false,
  isControlShow: false,
  rtpList: [] as any[],
  userControl: {
    game_ids: [],
    user_ids: [],
    rtp: 70,
    switch: 1,
    auto_cancel_rtp: 0
  },
  userControlList: [] as any[],
  gameList: [] as any[],
})

watch(
  () => props.show,
  async (val) => {
    if (val) {
      getGameRtp(0, 39)
      data.gameList = []
      indexStore.gameArray.forEach((item:any)=> {
        if(item.type==1){
          data.gameList.push(item)
        }
      })
    }
  }
)

const operatorTypeShow = (!indexStore.is_general_agent || indexStore.userInfo.operator_type) ? true:false

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}

const getSearchList = async () => {
  data.list = []
  data.total = 0
  data.userControlList = []
  let query = JSON.parse(JSON.stringify(data.query));
  query = setTimeValue(query)
  query.flag = '1'
  if (!query.search_value && query.agent_id == -1) {
    return ElMessage.error('请至少选择一个商户操作或者输入玩家ID/昵称查询')
  }
  if(query.today_bet){
    query.today_bet = BigTimeWan(query.today_bet)
  }
  if(query.total_bet){
    query.total_bet = BigTimeWan(query.total_bet)
  }
  if(query.today_game_income){
    query.today_game_income = BigTimeWan(query.today_game_income)
  }
  if(query.total_game_income){
    query.total_game_income = BigTimeWan(query.total_game_income)
  }
  indexStore.setModuleLoading(true)
  let res = await getPlayer(query)
  data.list = res.data.list
  data.total = res.data.total
}

const getGameRtp = async (id: number, game_id: number) => {
  let res = await getOperatorTiger({
    agent_id: id, game_id: game_id
  }) as any
  data.rtpList = setArrRtP(res.data.a_slots_rtpshow)
}

// 选择玩家
const playerControl = (val: any) => {
  data.userControlList = val
}
const addControl = throttle(async () => {
  let query = JSON.parse(JSON.stringify(data.userControl));
  query.user_ids = []
  data.userControlList.forEach((item: any) => {
    query.user_ids.push(item.agent_id + '_' + item.account3d_id)
  })
  query.switch = 2
  query.rtp = BigTimeHundred(query.rtp)
  query.auto_cancel_rtp = BigTimeHundred(query.auto_cancel_rtp)
  
  // 选择全部
  const allGame = query.game_ids.find((item: number) => item == -1)
  if (allGame) {
    query.game_ids = []
    data.gameList.forEach((item: any) => {
      query.game_ids.push(item.value)
    })
  }
  if(!query.game_ids.length){
    return ElMessage.error('请选择要调控的游戏')
  }
  indexStore.setModuleLoading(true)
  await changeAllControlUser(query)
  ElMessage.success('新增RTP调控成功')
  onHideDetails()
}, 5000)

// 选择全部游戏
const chooseGameType = async (row: any) => {
  const all = row.find((item: number) => item == -1)
  if (all) {
    data.userControl.game_ids = [-1] as any
  } else {
    data.userControl.game_ids = row
  }
}

const setArrRtP = (str: string) => {
  let arr = [], newArr: any[] = []
  arr = setCommaToArr(str)
  arr.forEach((item: any) => {
    newArr.push(BigHundred(item))
  })
  return newArr
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}

const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}

// 重置
const OperatorRef = ref<any>()
const onHideDetails = (show?:boolean) => {
  data.isControlShow = false
  data.userControlList = []
  data.userControl = {
    game_ids: [],
    user_ids: [],
    rtp: 70,
    switch: 1,
    auto_cancel_rtp: 0
  }
  if(show){
    data.query = {
      page: 1,
      size: 50,
      status: -1,
      search_type: 1,
      search_value: '',
      time_type: 2,
      agent_id: -1,
      operated_id: -1,
      is_online: -1,
      today_bet: '',
      total_bet: '',
      today_game_income: '',
      total_game_income: '',
      date: getSevenWeek()
    }
    OperatorRef.value.onHideDetails()
    getSearchList()
  }
}
const emit = defineEmits(['onHideDetails'])
const handleClose = async () => {
  onHideDetails()
  emit('onHideDetails', false)
}
</script>

<style scoped lang="scss"></style>
